package cxy.highConcurrency;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureDemo_5 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		System.out.println("1:" + Thread.currentThread().getName());
		
		CompletableFuture<String> f0 = CompletableFuture.supplyAsync(() ->{System.out.println("2:" + Thread.currentThread().getName());
			for (int i = 0; i < 1000; i++) {
				int a = i;
			}
			System.out.println("异步执行 Hello World");
			return "Hello World";}); // ①
		
		System.out.println("f0.get()before");
		//CompletableFuture的get()方法值会阻塞主线程，直到子线程执行任务完成返回结果才会取消阻塞。
		//如果子线程一直不返回接口那么主线程就会一直阻塞，所以我们一般不建议直接使用CompletableFuture的get()方法，
		//而是使用future.get(5, TimeUnit.SECONDS);方法指定超时时间。
		f0.get();
		System.out.println("f0.get()after");
		
		f0.thenRun(() -> {
			System.out.println("3:" + Thread.currentThread().getName());
		});
		
		f0.thenRunAsync(() -> {
			System.out.println("4:" + Thread.currentThread().getName());
		});
		
	}
}
